﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using AutoMapper;
using Prism.Commands;
using Prism.Regions;
using YJTTool.Common.Helper;
using YJTTool.Core;
using YJTTool.Core.Global;
using YJTTool.CustomerInfo.Model;
using YJTTool.DBBaseServer.AbstractModel;
using YJTTool.DBBaseServer.Entities;

namespace YJTTool.CustomerInfo.ViewModels
{
    public class CustomerInfoViewModel : InheritBase, INavigationAware
    {
        #region 内部字段
        private readonly AbstractTelematicsServer abstractTelematics;
        private readonly IMapper _mapper;
        #endregion

        #region ctor
        public CustomerInfoViewModel(AbstractTelematicsServer abstractTelematics, IMapper mapper)
        {
            this.abstractTelematics = abstractTelematics;
            _mapper = mapper;
            TelematicsItem = new TelematicsDto();
            SaveCommand = new DelegateCommand(Save);
            ResetCommand = new DelegateCommand(Reset);
            QueryCommand = new DelegateCommand(async () =>{ await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await TelematicsQuery()); });
            CopyCellContentCommand = new DelegateCommand<object>(ExecuteCopyCellContent);
            Telematics = new ObservableCollection<TelematicsDto>();
            DataBaseTypeList = new ObservableCollection<string>(GlobalApp.Instance.DataBaseType);
            TelematicsNameList = new ObservableCollection<string>(GlobalApp.Instance.TelematicsName);
            Init();
        }
        #endregion

        #region 属性
        private TelematicsDto telematicsItem;
        public TelematicsDto TelematicsItem
        {
            get => telematicsItem;
            set
            {
                telematicsItem = value;
                RaisePropertyChanged();
            }
        }
        private string searchText;
        public string SearchText
        {
            get => searchText;
            set
            {
                searchText = value;
                RaisePropertyChanged();
            }
        }


        #endregion

        #region 命令
        public DelegateCommand<object> CopyCellContentCommand { get; private set; }

        public DelegateCommand ResetCommand { get; private set; }

        public DelegateCommand SaveCommand { get; private set; }

        public DelegateCommand QueryCommand { get; private set; }
        #endregion

        #region 集合
        private ObservableCollection<TelematicsDto> _telematics;
        public ObservableCollection<TelematicsDto> Telematics
        {
            get { return _telematics; }
            set
            {
                if (_telematics != value)
                {
                    _telematics = value;
                    RaisePropertyChanged();
                }
            }
        }

        public ObservableCollection<string> TelematicsNameList { get; private set; }

        public ObservableCollection<string> DataBaseTypeList { get; private set; }
        #endregion

        #region 方法
        /// <summary>
        /// 将内容复制到剪贴板
        /// </summary>
        /// <param name="parameter"></param>
        private void ExecuteCopyCellContent(object parameter)
        {
            if (parameter is string content)
            {
                Clipboard.SetText(content);
            }
        }

        private void Reset()
        {
            TelematicsItem = new TelematicsDto();
        }

        private async void Save()
        {
            var list = CheckFields(TelematicsItem);

            if (list.Count > 2)
            {
                MessageError("请将信息填写完整后再进行保存！");
            }
            if (TelematicsItem != null)
            {
                TelematicsItem.AddDate = DateTime.Now;
                TelematicsItem.CreatePeople = GlobalApp.Instance.UserName;
                telematics telematics = _mapper.Map<telematics>(TelematicsItem);

                var _tmcount = Telematics.Where(s => s.Id == TelematicsItem.Id).ToArray();
                if (_tmcount.Count() > 0)
                {
                    await abstractTelematics.UpdateAsync(telematics);
                    MessageSuccess("更新成功！");
                }
                else
                {
                    await abstractTelematics.InsertAsync(telematics);
                    MessageSuccess("保存成功！");
                }
                await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await TelematicsQuery());
            }
        }
        private async void Init()
        {
            await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await TelematicsQuery());
        }

        private async Task TelematicsQuery()
        {
            await Task.Run( () => 
            {
                List<telematics> data =  abstractTelematics.Query();
                if (!string.IsNullOrEmpty(SearchText))
                {
                    var filtrationList = data.Where(s => s.StoresName.Contains(SearchText) || s.StoresCode.Contains(SearchText, StringComparison.OrdinalIgnoreCase)).ToArray();
                    if (filtrationList != null && filtrationList.Count() > 0)
                    {
                        List<TelematicsDto> telematics = _mapper.Map<List<TelematicsDto>>(filtrationList.ToList());
                        Telematics = new ObservableCollection<TelematicsDto>();
                        telematics.ForEach(s => { Telematics.Add(s); });
                    }
                    else
                    {
                        Telematics = new ObservableCollection<TelematicsDto>();
                    }
                }
                else
                {
                    if (data != null)
                    {
                        List<TelematicsDto> telematics = _mapper.Map<List<TelematicsDto>>(data.ToList());
                        Telematics = new ObservableCollection<TelematicsDto>();
                        telematics.ForEach(s => { Telematics.Add(s); });
                    }
                    else
                    {
                        Telematics = new ObservableCollection<TelematicsDto>();
                    }
                }
            });
        }
        #endregion

        #region 导航
        public void OnNavigatedTo(NavigationContext navigationContext)
        {

        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
        #endregion
    }
}
